package com.ruoyi.gp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gp.domain.Options;
import com.ruoyi.gp.domain.bo.OptionsBo;
import com.ruoyi.gp.domain.vo.OptionsVo;
import com.ruoyi.gp.mapper.OptionsMapper;
import com.ruoyi.gp.service.IOptionsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.gp.domain.bo.QuestionBo;
import com.ruoyi.gp.domain.vo.QuestionVo;
import com.ruoyi.gp.domain.Question;
import com.ruoyi.gp.mapper.QuestionMapper;
import com.ruoyi.gp.service.IQuestionService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 问题Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-08
 */
@RequiredArgsConstructor
@Service
public class QuestionServiceImpl implements IQuestionService {

    private final QuestionMapper baseMapper;

    private final IOptionsService iOptionsService;


    /**
     * 查询问题
     */
    @Override
    public QuestionVo queryById(Long questionId){
        return baseMapper.selectVoById(questionId);
    }

    /**
     * 查询问题列表
     */
    @Override
    public TableDataInfo<QuestionVo> queryPageList(QuestionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Question> lqw = buildQueryWrapper(bo);
        Page<QuestionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询问题列表
     */
    @Override
    public List<QuestionVo> queryList(QuestionBo bo) {
        LambdaQueryWrapper<Question> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Question> buildQueryWrapper(QuestionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Question> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSurveyId() != null, Question::getSurveyId, bo.getSurveyId());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), Question::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), Question::getType, bo.getType());
        lqw.eq(bo.getRequired() != null, Question::getRequired, bo.getRequired());
        lqw.eq(bo.getOrderStyle() != null, Question::getOrderStyle, bo.getOrderStyle());
        return lqw;
    }

    /**
     * 新增问题
     */
    @Override
    public Boolean insertByBo(QuestionBo bo) {
        Question add = BeanUtil.toBean(bo, Question.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        bo.getOptions().stream().forEach(optionsBo -> {
            optionsBo.setQuestionId(add.getQuestionId());
            iOptionsService.insertByBo(optionsBo);
        });
        if (flag) {
            bo.setQuestionId(add.getQuestionId());
        }
        return flag;
    }

    /**
     * 修改问题
     */
    @Override
    public Boolean updateByBo(QuestionBo bo) {
        Question update = BeanUtil.toBean(bo, Question.class);
        validEntityBeforeSave(update);
        Boolean flag=baseMapper.updateById(update)> 0;
        bo.getOptions().stream().forEach(optionsBo -> {
            optionsBo.setQuestionId(update.getQuestionId());
            iOptionsService.updateByBo(optionsBo);
        });
        return flag ;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Question entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除问题
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            ids.stream().forEach(questionId -> {
                List<Long> optionsIds = new ArrayList<>();
                OptionsBo optionsBo = new OptionsBo();
                optionsBo.setQuestionId(questionId);
                List<OptionsVo> optionsVos = iOptionsService.queryList(optionsBo);
                Boolean b =true;
                if(ObjectUtil.isNotEmpty(optionsVos)){
                for (OptionsVo optionsVo : optionsVos) {
                    optionsIds.add(optionsVo.getOptionId());
                }
                b = iOptionsService.deleteWithValidByIds(optionsIds,true);
                }
                if(!b){
                    throw new RuntimeException("删除问题失败");
                }
            });

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<QuestionVo> queryByQuestion(Long sid) {

        return baseMapper.queryByQuestion(sid);
    }
}
